package com.sa07.net;

import com.sa07.exception.SatpHeaderInvalidException;

/**
 * satp包头部
 * 
 * @author Long.shangbo
 * 
 *         2014-2-19 下午10:36:42
 */
public class SatpPacketHeader {

	public static final int SATP_PACKET_HEADER_LEN = 6;

	/**
	 * 命令字（两个字节）
	 */
	private short cmd = 0;

	/**
	 * num + next + 内容的长度（两个字节）
	 */
	private short len = 0;

	/**
	 * 用于区分不同批次的下发命令（一个字节）
	 */
	private byte num = 0;

	/**
	 * 是否有后续命令(0：无后续命令， 1：有后续命令)（一个字节）
	 */
	private byte next = 0;

	private byte[] byteData = null;

	public SatpPacketHeader(short cmd, short len, byte num, byte next) {
		this.cmd = cmd;
		this.len = len;
		this.num = num;
		this.next = next;
		// 解码成无符号的字节数组
		createByteData();
	}

	public SatpPacketHeader() {

	}

	public short getCmd() {
		return cmd;
	}

	public void setCmd(short cmd) {
		this.cmd = cmd;
	}

	public short getLen() {
		return len;
	}

	public void setLen(short len) {
		this.len = len;
	}

	public byte getNum() {
		return num;
	}

	public void setNum(byte num) {
		this.num = num;
	}

	public byte getNext() {
		return next;
	}

	public void setNext(byte next) {
		this.next = next;
	}

	public byte[] getByteData() {
		return byteData;
	}
	
	public void setByteData(byte[] bt) {
		if (bt == null || bt.length != SATP_PACKET_HEADER_LEN) {
			throw new SatpHeaderInvalidException("The header data is invalid...");
		}

		decodeByteData(bt);
	}

	private void decodeByteData(byte[] bt) {
		this.cmd = (short) ((bt[0] & 0xff << 8) | (bt[1] & 0xff));
		this.len = (short) ((bt[2] & 0xff << 8) | (bt[3] & 0xff));
		this.num = (byte) (bt[4] & 0xff);
		this.next = (byte) (bt[5] & 0xff);
	}

	/**
	 * 创建成字节数据
	 */
	private void createByteData() {
		this.byteData = new byte[SATP_PACKET_HEADER_LEN];
		this.byteData[0] = (byte) (this.cmd >> 8 & 0xff);
		this.byteData[1] = (byte) (this.cmd & 0xff);
		this.byteData[2] = (byte) (this.len >> 8 & 0xff);
		this.byteData[3] = (byte) (this.len & 0xff);
		this.byteData[4] = (byte) (this.num & 0xff);
		this.byteData[5] = (byte) (this.next & 0xff);
	}

}
